<?php
/**
+-----------------------------------------------------------------------------------------------
* GouGuOPEN [ 左手研发，右手开源，未来可期！]
+-----------------------------------------------------------------------------------------------
* @Copyright (c) 2021~2024 http://www.gouguoa.com All rights reserved.
+-----------------------------------------------------------------------------------------------
* @Licensed 勾股OA，开源且可免费使用，但并不是自由软件，未经授权许可不能去除勾股OA的相关版权信息
+-----------------------------------------------------------------------------------------------
* @Author 勾股工作室 <hdm58@qq.com>
+-----------------------------------------------------------------------------------------------
*/

declare (strict_types = 1);

namespace app\contract\controller;

use app\base\BaseController;
use app\contract\model\ContractType;
use app\contract\validate\TypeValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;

class Type extends BaseController
{
    protected $model;
    
    public function __construct()
    {
        parent::__construct();
        $this->model = new ContractType();
    }

    /**
     * 合同类型列表 - GET /contract/type/index
     */
    public function index(): Json
    {
        $param = get_params();
        
        $where = [];
        $where[] = ['delete_time', '=', 0];
        
        // 关键词搜索
        if (!empty($param['keywords'])) {
            $where[] = ['title|remark', 'like', '%' . $param['keywords'] . '%'];
        }
        
        // 状态筛选
        if (isset($param['status']) && $param['status'] !== '') {
            $where[] = ['status', '=', $param['status']];
        }
        
        $list = $this->model->datalist($param, $where);
        return to_assign(0, '获取成功', $list);
    }

    /**
     * 查看合同类型详情 - GET /contract/type/show
     */
    public function show(): Json
    {
        $param = get_params();
        $id = $param['id'] ?? 0;
        
        if (empty($id)) {
            return to_assign(1, '参数错误');
        }
        
        $detail = $this->model->getById($id);
        if (empty($detail)) {
            return to_assign(1, '数据不存在');
        }
        
        return to_assign(0, '获取成功', $detail);
    }

    /**
     * 新增合同类型 - POST /contract/type/store
     */
    public function store(): Json
    {
        $param = get_params();
        
        try {
            validate(TypeValidate::class)->scene('add')->check($param);
        } catch (ValidateException $e) {
            return to_assign(1, $e->getError());
        }
        
        $param['admin_id'] = $this->uid;
        $param['create_time'] = time();
        
        $result = $this->model->add($param);
        if ($result) {
            return to_assign(0, '添加成功');
        } else {
            return to_assign(1, '添加失败');
        }
    }

    /**
     * 更新合同类型 - PUT /contract/type/update
     */
    public function update(): Json
    {
        $param = get_params();
        
        if (empty($param['id'])) {
            return to_assign(1, '参数错误');
        }
        
        try {
            validate(TypeValidate::class)->scene('edit')->check($param);
        } catch (ValidateException $e) {
            return to_assign(1, $e->getError());
        }
        
        $param['update_time'] = time();
        
        $result = $this->model->edit($param);
        if ($result) {
            return to_assign(0, '更新成功');
        } else {
            return to_assign(1, '更新失败');
        }
    }

    /**
     * 删除合同类型 - DELETE /contract/type/destroy
     */
    public function destroy(): Json
    {
        $param = get_params();
        $id = $param['id'] ?? 0;
        
        if (empty($id)) {
            return to_assign(1, '参数错误');
        }
        
        // 检查是否有关联的合同
        $count = Db::name('Contract')->where('type_id', $id)->where('delete_time', 0)->count();
        if ($count > 0) {
            return to_assign(1, '该类型下还有合同数据，无法删除');
        }
        
        $result = $this->model->delById($id);
        if ($result) {
            return to_assign(0, '删除成功');
        } else {
            return to_assign(1, '删除失败');
        }
    }

    /**
     * 更新合同类型状态 - POST /contract/type/status
     */
    public function status(): Json
    {
        $param = get_params();
        
        if (empty($param['id']) || !isset($param['status'])) {
            return to_assign(1, '参数错误');
        }
        
        $result = Db::name('ContractType')
            ->where('id', $param['id'])
            ->update([
                'status' => $param['status'],
                'update_time' => time()
            ]);
            
        if ($result) {
            return to_assign(0, '状态更新成功');
        } else {
            return to_assign(1, '状态更新失败');
        }
    }

    /**
     * 获取合同类型选项 - GET /contract/type/options
     */
    public function options(): Json
    {
        $where = [];
        $where[] = ['delete_time', '=', 0];
        $where[] = ['status', '=', 1]; // 只获取启用状态的类型
        
        $list = Db::name('ContractType')
            ->where($where)
            ->field('id,title,remark')
            ->order('sort desc,id asc')
            ->select()
            ->toArray();
            
        return to_assign(0, '获取成功', $list);
    }

    /**
     * 排序 - POST /contract/type/sort
     */
    public function sort(): Json
    {
        $param = get_params();
        
        if (empty($param['id']) || !isset($param['sort'])) {
            return to_assign(1, '参数错误');
        }
        
        $result = Db::name('ContractType')
            ->where('id', $param['id'])
            ->update([
                'sort' => intval($param['sort']),
                'update_time' => time()
            ]);
            
        if ($result !== false) {
            return to_assign(0, '排序更新成功');
        } else {
            return to_assign(1, '排序更新失败');
        }
    }
}